/*
 * Copyright (c) 2007 Team and Concepts Limited.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Team and Concepts Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY TEAM AND CONCEPTS LIMITED ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TEAM AND CONCEPTS LIMITED BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.IO;
using System.Globalization;

namespace EditGrid.API.Client.Atom
{
    public class AtomEntry
    {
        private Uri editUri;
        private string atomId;
        private string atomUpdated;
        private string resourceType;
        private string resourcePath;
        protected Dictionary<string,string> editGridElements = new Dictionary<string,string>();
        private bool isCreate = true;

        public Dictionary<string, string> EditGridElements
        {
            get { return this.editGridElements; }
        }

        public string ResourceType
        {
            get { return this.resourceType; }
        }

        public string ResourcePath
        {
            get { return this.resourcePath; }
        }

        public Uri EditUri
        {
            get { return this.editUri; }
        }

        public string Updated
        {
            get { return this.atomUpdated; }
        }

        public bool IsCreate
        {
            get { return this.isCreate; }
        }

        public AtomEntry()
        {
        }

        public AtomEntry(string resourceType, string resourcePath)
        {
            this.resourceType = resourceType;
            this.resourcePath = resourcePath;
        }

        internal static AtomEntry LoadXml(XmlElement element)
        {
            AtomEntry entry = new AtomEntry();
            entry.LoadXml(new List<string>(), element);
            return entry;
        }

        protected void LoadXml(List<String> elementStack, XmlElement element)
        {
            this.isCreate = false;

            XmlNodeList nodeList = element.ChildNodes;

            IEnumerator i = nodeList.GetEnumerator();
            bool hasInnerElement = false;
            while (i.MoveNext())
            {
                XmlNode n = (XmlNode)i.Current;
                if (n.NodeType == XmlNodeType.Element)
                {
                    hasInnerElement = true;
                    XmlElement e = (XmlElement)n;
                    if (e.NamespaceURI == Properties.Settings.Default.EditGridNS)
                    {
                        elementStack.Add(e.LocalName);
                        this.LoadXml(elementStack, e);
                    }
                    else if (AtomUtil.IsAtomElement(e, "id"))
                    {
                        string text = e.InnerText;
                        int pos = text.IndexOf(':');
                        this.resourceType = text.Substring(0, pos);
                        this.resourcePath = text.Substring(pos + 1);
                        this.atomId = text;
                    }
                    else if (AtomUtil.IsAtomElement(e, "link") && e.GetAttribute("rel") == "edit")
                    {
                        this.editUri = new Uri(e.GetAttribute("href"));
                    }
                    else if (AtomUtil.IsAtomElement(e, "updated"))
                    {
                        this.atomUpdated = e.InnerText;
                    }
                }
            }

            if (!hasInnerElement)
            {
                this.editGridElements[String.Join(".", elementStack.ToArray())] = element.InnerText;
            }

            if (elementStack.Count > 0) elementStack.RemoveAt(elementStack.Count - 1);
        }

        public string ToAtomAsString()
        {
            TextWriter writer = new StringWriter();
            XmlTextWriter w = new XmlTextWriter(writer);
            w.WriteStartElement("entry");
            w.WriteAttributeString("xmlns", Properties.Settings.Default.AtomNS);
            w.WriteAttributeString("xmlns", "eg", null, Properties.Settings.Default.EditGridNS);
            foreach (KeyValuePair<string, string> pair in editGridElements)
            {
                w.WriteStartElement(pair.Key, Properties.Settings.Default.EditGridNS);
                w.WriteString(pair.Value);
                w.WriteEndElement();
            }
            w.WriteEndElement();
            w.Close();
            return writer.ToString();
        }

        public string ToRequestPath()
        {
            return this.resourceType + "/" + this.resourcePath;
        }

        public void SetValue(string key, string value)
        {
            this.editGridElements[key] = value;
        }

        public string GetValue(string key)
        {
            if (this.editGridElements.ContainsKey(key))
            {
                return this.editGridElements[key];
            }
            else
            {
                return "";
            }
        }

        public bool GetBooleanValue(string key)
        {
            return AtomUtil.AsBoolValue(this.GetValue(key));
        }

        public int GetIntValue(string key)
        {
            return int.Parse(this.GetValue(key));
        }

        public long GetLongValue(string key)
        {
            return long.Parse(this.GetValue(key));
        }

        public DateTime GetDateTimeValue(string key)
        {
            return DateTime.ParseExact(this.GetValue(key), "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.CurrentCulture);
        }

        public override string ToString()
        {
            return this.resourceType + "/" + this.resourcePath;
        }
    }
}
